#include <head.h>



typedef struct data
{
    FILE* fp1;
    FILE* fp2;
    int   seek1;
    int   seek2;
}DATA;

void * fun1(void *arg){
    printf("我是子线程1  拷贝前一半\n");
    DATA *a = (DATA*)arg;
    char buff[64] = {0};
    int flag = 0;
    fseek(a->fp1,0,SEEK_SET);
    fseek(a->fp2,0,SEEK_SET);
    while ((a->seek1-flag) > sizeof(buff))
    {
        fread(buff,sizeof(buff),1,a->fp1);
        fwrite(buff,sizeof(buff),1,a->fp2);
        flag+=sizeof(buff);
        printf("拷贝次数1\n");
    }
    fread(buff,a->seek1-flag,1,a->fp1);
    fwrite(buff,a->seek1-flag,1,a->fp2);
    
}
void * fun2(void *arg){
    sleep(2);
    printf("我是子线程2 我拷贝后一半\n");
    DATA*a = (DATA*)arg;
    
    char buff[64] = {0};
    int flag = a->seek1;
    fseek(a->fp1,a->seek1,SEEK_SET);
    fseek(a->fp2,a->seek1,SEEK_SET);
    while (a->seek2 > flag)
    {
        fread(buff,sizeof(buff),1,a->fp1);
        fwrite(buff,sizeof(buff),1,a->fp2);
        flag+=sizeof(buff);
        printf("拷贝次数2\n");
    }
   
    //exit(1);
}

int main(int argc, char const *argv[])
{
    if(argc < 2){
        ERROR("参数不够");
        exit(-1);
    }
    printf("我是主线程\n");
    DATA a;
    
    //打开两个文件 并返回参数给结构体
    a.fp1 = fopen(argv[1],"rb");
    if(NULL == a.fp1){
        ERROR("文件打开失败");
        exit(-1);
    }
    a.fp2= fopen("new.txt","wb");
    if(NULL == a.fp2){
        ERROR("文件打开失败");
        exit(-1);
    }
    //获取文件大小 
    fseek(a.fp1,0,SEEK_END);
    int len = ftell(a.fp1);
    printf(" 文件大小 %d",len);
    a.seek1 = len / 2;
    a.seek2 = len;
    
    pthread_t tid1,tid2;
    //进程间拷贝文件 用结构体传递
    if( 0 != pthread_create(&tid1,NULL,fun1,&a)){
        printf("子线程1创建失败\n");
        exit(-1);
    }
    if( 0 != pthread_create(&tid2,NULL , fun2,&a)){
        ERROR("线程2创建失败");
        exit(-1);
    }
    
    
    printf("hello world\n");
    //线程等待
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);

    //关闭文件   注意关闭
    fclose(a.fp1);
    fclose(a.fp2);
    return 0;
    
}